package com.thread.queue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityBlockingQueueTest {

    public static void main(String[] args) {
        BlockingQueue<PriorityItem> queue = new PriorityBlockingQueue();
        Random random = new Random();
        System.out.println("先随机生成5个数放入队列！");
        for (int i = 0; i < 5; i++) {
            int i1 = random.nextInt(10);
            queue.add(new PriorityItem(i1));
            System.out.println("Producer : " + i1);
        }
        System.out.println("从队列中获取值！");
        for(;;){
            try {
                System.out.println("Consumer : " + queue.take().getIndex());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class PriorityItem implements Comparable {

        private int index;

        public PriorityItem(int index) {
            this.index = index;
        }

        public int getIndex() {
            return index;
        }

        @Override
        public int compareTo(Object o) {
            PriorityItem item = (PriorityItem) o;
            if(this.getIndex() > item.getIndex()){
                return 1;
            }else if(this.getIndex() < item.getIndex()){
                return -1;
            }
            return 0;
        }
    }
}
